package com.ncepu.clubmanagement.controller;


import com.ncepu.clubmanagement.anno.CommitteePermission;
import com.ncepu.clubmanagement.pojo.*;
import com.ncepu.clubmanagement.service.ClubService;
import com.ncepu.clubmanagement.service.PersonService;
import com.ncepu.clubmanagement.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ClubService clubService;

    @GetMapping("/self")
    public Result getSelfInfo(){
        log.info("获取本人信息");

        String jwt = request.getHeader("token");

        Claims claims = jwtUtils.parseJWT(jwt);

        String account = (String)claims.get("account");
        // 获取到用户信息
        PersonWithSchoolName personWithSchoolName = personService.getInfoByAccount(account);

        return Result.success(personWithSchoolName);
    }

    // 获取用户权限，但是和实际后端存储的权限方式不同
    @GetMapping("/permission")
    public Result getPermissionOfFourLevel() {
        log.info("获取用户权限(4级权限体系) (PersonController.java)");
        // 获取jwt并解析其中账户信息
        String jwt = request.getHeader("token");
        Claims claims = jwtUtils.parseJWT(jwt);
        String account = (String)  claims.get("account");
        PermissionOfFourLevel permissionOfFourLevel = personService.getPermissionOfFourLevel(account);
        return Result.success(permissionOfFourLevel);
    }

    @PutMapping("/self")
    public Result modifySelfInfo(@RequestBody Person person){
        log.info("修改本人信息");
        // 修改本人信息
        // 先获取到本人的jwt中的账号信息，并进行修改
        String jwt = request.getHeader("token");
        Claims claims = jwtUtils.parseJWT(jwt);
        String account = (String)claims.get("account");
        person.setAccount(account);

        personService.modifyPersonInfo(person);
        return Result.success();
    }

    @GetMapping("/idAndName")
    public Result getAllBasePersonInfo(String userName){
        List<BasePerson> basePerson = personService.getAllBasePersonInfoByUserName(userName);
        return Result.success(basePerson);
    }

    @PutMapping("/password/self")
    public Result modifySelfPassword(@RequestBody PasswordChange passwordChange) throws Exception{
        // jwt获取账号
        String jwt = request.getHeader("token");
        Claims claims = jwtUtils.parseJWT(jwt);
        String account = (String)claims.get("account");
        // 通过服务判断
        boolean result = personService.modifySelfPassword(account, passwordChange.getPassword(), passwordChange.getNewPassword());

        if(result)
            return Result.success();
        else
            return Result.error("old password error");
    }

    @CommitteePermission
    @GetMapping("/list/committee")
    public Result getPersonListByCommittee(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")Integer pageSize, Integer clubId,String userName){
        log.info("获取人员信息列表");
        PageBean personBasicInfoList = personService.getPersonBasicInfoList(page, pageSize,clubId,userName);
        return Result.success(personBasicInfoList);
    }

    @GetMapping("/list")
    public Result getPersonList(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")Integer pageSize,Integer clubId,String userName){
        log.info("获取人员信息列表");

        // jwt获取信息
        String jwt = request.getHeader("token");
        Claims claims = jwtUtils.parseJWT(jwt);
        Integer personId = (Integer)claims.get("id");

        if(clubId != null){  // 查询在某个社团内的人员信息
            // 判定是否在此社团
            boolean isJoined = clubService.isManaged(personId, clubId);
            if(!isJoined){
                return Result.error("查看了其它社团的人员信息");
            }
            PageBean personBasicInfoList = personService.getPersonBasicInfoList(page, pageSize,clubId,userName);
            return Result.success(personBasicInfoList);
        }
        else // 查询所有管理的人员信息
        {
            PageBean personBasicInfoList = personService.getManagedPersonBasicInfoList(page, pageSize,userName,personId);
            return Result.success(personBasicInfoList);
        }

    }

    @PutMapping("/password/reset")
    @CommitteePermission
    public Result resetPassword(@RequestParam Integer personId){
        log.info("重置密码");
        personService.resetPassword(personId);
        return Result.success();
    }

    @GetMapping()
    public Result getPersonInfo(@RequestParam(name = "personId") Integer targetPersonId){
        log.info("获取特定人员信息");
        // jwt解析请求用户id
        String jwt = request.getHeader("token");
        Claims claims = jwtUtils.parseJWT(jwt);
        Integer sourcePersonId = (Integer)claims.get("id");

        // 2.检查是否管理该人员（是否有权限）
        boolean isManage = personService.checkIsManaged(sourcePersonId, targetPersonId);
        if(!isManage){
            return Result.error("无权限查看此人信息");
        }
        // 3.实际调用服务查询
        PersonFontOfGetDetail detail = personService.getPersonInfoWithoutPassword(targetPersonId);
        return Result.success(detail);
    }

}
